﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Text;
using System.IO;

namespace BlackListDataSyn
{
   public class LogHelper
    {
       public LogHelper()
       {
           GetLogPath();
       }

       private string m_szFile = "";   //日志文件
       public string GetLogPath()
       {
           string szFile = string.Format("BlacklistLog_{0}.txt", DateTime.Now.ToString("yyyyMMdd"));
           string szDir = PlatformConfig.CurrentPath;
           if (szDir == "\\") szDir = "";
           szDir += "\\Log\\";

           m_szFile = szDir + "\\" + szFile;
           if (!Directory.Exists(szDir))
               Directory.CreateDirectory(szDir);
           return m_szFile;
       }

       const int WRITE_MAXL = 200000000;    //大约200M
       public static LogHelper m_logFile = new LogHelper();
       public static LogHelper Instance
       {
           get { return m_logFile; }
       }

       public string ReadFileLog()
       {
           string szLog = "";
           try
           {
               StreamReader sr = null;
               int length = 1024 * 1024;
               char[] buffer = new char[length];
               sr = new StreamReader(m_szFile, Encoding.UTF8);
               sr.Read(buffer, 0, length);
               szLog = new string(buffer);
               sr.Close();
           }
           catch (IOException ex)
           {
               szLog = "";
           }
           return szLog;
       }

       //写日志
       public  bool WriteFileLog(string sLog)
       {

           FileInfo fInfo = new FileInfo(m_szFile);
           if (fInfo.Exists)
           {
               if (fInfo.Length >= WRITE_MAXL)
               {
                   //fInfo.Delete();
                   //fInfo.MoveTo());
                   GetLogPath();
               }
           }
           else
               GetLogPath();


           StringBuilder sb = new StringBuilder();
           //sb.Append(DateTime.Now.ToString()).Append("\t").Append(sLog);
           sb.Append(sLog);
           try
           {
               StreamWriter sw = null;
               sw = new StreamWriter(m_szFile, true, Encoding.UTF8);
               sw.WriteLine(sb.ToString());

               //清空缓冲区
               sw.Flush();

               //关闭流
               sw.Close();
           }
           catch (IOException ex)
           {
               sb.Append(ex.Message);
               return false;
           }
           return true;
       }

    }
}
